package com.iweb.service;

import com.common.datasource.DataSourceUtil;
import com.iweb.dao.UserDao;
import com.iweb.dao.UserDaoImpl;
import com.iweb.pojo.User;

/*
 *作者：lth
 *时间：2020/8/11 18:10
 *描述：
 */
public class UserService {
    public boolean addUser(User user) {
        //连接数据库
        DataSourceUtil dataSourceUtil = new DataSourceUtil();
        dataSourceUtil.init();
        UserDao userDao = new UserDaoImpl(dataSourceUtil.getConnection());
        User finduser = null;
        try {
            finduser = userDao.findByUserId(user.getUserid());
            //如果存在重复用户，则抛出异常
            if (finduser != null) {
                throw new RuntimeException();
            }
            user.setPhone(user.getUserid());
            userDao.save(user);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            dataSourceUtil.close();
        }
        return true;
    }

    public User findByUserId(String userid) {
        User user = null;
        // 链接数据库
        DataSourceUtil dataSourceUtil = new DataSourceUtil();
        dataSourceUtil.init();
        // 创建数据库操作对象
        UserDao userDao = new UserDaoImpl(dataSourceUtil.getConnection());
        try {
            // 业务逻辑
            user = userDao.findByUserId(userid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dataSourceUtil.close();
        }
        return user;
    }
}
